﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using Table_Dal;
using System.Collections;
using BLL;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms.DataVisualization.Charting;
using System.Linq;
using System.Diagnostics;
namespace ApplicationLayer
{
    public partial class frmGiaiThuatGEN : DevComponents.DotNetBar.OfficeForm
    {
        public frmGiaiThuatGEN()
        {
            InitializeComponent();
        }
        YeuCauDeThi_GiaiThuatTbl DeThi_GT; //các yêu cầu của đề thi (tỉ lệ độ khó của đề bài)
        MonHoc_GiaiThuatTbl Mon_GT;        //các yêu cầu của đề thi (môn)
        List<Chuong_GiaiThuatTbl> ArrChuong_GT; //các yêu cầu của đề thi (các chương và % kiến thức)
        bool GTTuDong = false;                  // = false nếu làm giải thuật GEN "từng bước" || = true nếu giải thuật GEN "Tự Động"
        float TiLeDotBien;
        int SoDeThiBanDau;
        List<DeThi_GiaiThuatTbl> dsDeThi;
        GiaiThuatGen gtgen;
        string user = "";
        DeThi_GiaiThuatTbl decantao;
        public frmGiaiThuatGEN(YeuCauDeThi_GiaiThuatTbl dethi_gt, MonHoc_GiaiThuatTbl mon_gt, List<Chuong_GiaiThuatTbl> ArrChuong, bool giaithuat,string user)
        {
            this.user = user;
            GTTuDong = giaithuat;
            DeThi_GT = new YeuCauDeThi_GiaiThuatTbl();
            Mon_GT = new MonHoc_GiaiThuatTbl();
            ArrChuong_GT = new List<Chuong_GiaiThuatTbl>();
            DeThi_GT = dethi_gt;
            Mon_GT = mon_gt;
            ArrChuong_GT = ArrChuong;
            InitializeComponent();
        }
        List<CauHoi_GiaiThuatTbl> lstQuanThe;
        private void frmGiaiThuatGEN_Load(object sender, EventArgs e)
        {
            decantao = new DeThi_GiaiThuatTbl();
            lblSoCauhoi.Text = DeThi_GT.SoCauHoi.ToString();
            lblThoiGian.Text = DeThi_GT.ThoiGian.ToString();
            lbltendethi.Text = DeThi_GT.TenDeThi;
            lblMonHoc.Text = Mon_GT.TenMonHoc;
            expDeThi.SubItems.Clear();
            btnDotBien.Enabled = false;
            btnGhepCap.Enabled = false;
            btnLaiGhep.Enabled = false;
            DanhSachCauHoiBanDau();
            gtgen = new GiaiThuatGen(lstQuanThe);
            dgvQuanThe.DataSource = lstQuanThe;
            dgvQuanThe.Columns["NoiDung"].Width = 650;
            dgvQuanThe.Columns[0].Visible = false;
            pageSlider.SelectedPage = pageLoad;
            int count_RK = 0;
            int count_K = 0;
            int count_V = 0;
            int count_D = 0;
            int count_RD = 0;
            foreach (CauHoi_GiaiThuatTbl item in lstQuanThe)
            {
                if (item.DoKho == 1)
                    count_RD++;
                if (item.DoKho == 2)
                    count_D++;
                if (item.DoKho == 3)
                    count_V++;
                if (item.DoKho == 4)
                    count_K++;
                if (item.DoKho == 5)
                    count_RK++;
            }
            lblDoKho_RK.Text = "Rất Khó : " + count_RK + " câu";
            lblDoKho_K.Text = "Khó        : " + count_K + " câu";
            lblDoKho_Vua.Text = "Vừa        : " + count_V + " câu";
            lblDoKho_D.Text = "Dễ          : " + count_D + " câu";
            lblDoKho_RD.Text = "Rất Dễ   : " + count_RD + " câu";
            dgvQuanThe.ReadOnly = true;
            if (GTTuDong == false)
            {
                pageSlider.SelectedPage = pageLoad;
                btnKhoiTao.Enabled = true;
                btnGiaiThuat.Enabled = false;
                btnLuu.Enabled = false;
                btnReSet.Enabled = false;
            }
            else
            {
                btnKhoiTao.Enabled = false;
                btnGiaiThuat.Enabled = false;
                GiaithuatTuDong();
                btnLuu.Enabled = true;
            }
        }

        private void btnKhoiTao_Click(object sender, EventArgs e)
        {
            pageSlider.SelectedPage = pageKhoiTaoQuanThe;
            KhoiTaoQuanThe();
            lstDeThi_khoiTao.DataSource = dsDeThi;
            lstDeThi_khoiTao.DisplayMember = "TenDeThi";
            lstDeThi_khoiTao.ValueMember = "MaDeThi";
            btnKhoiTao.Enabled = false;
            btnGhepCap.Enabled = true;
        }

        private void DanhSachCauHoiBanDau()
        {
            CauHoiBll chbll;
            lstQuanThe = new List<CauHoi_GiaiThuatTbl>();
            foreach (Chuong_GiaiThuatTbl item in ArrChuong_GT)
            {
                chbll = new CauHoiBll();
                List<CauHoiTbl> lst = new List<CauHoiTbl>();
                lst = chbll.LayDanhSachCauHoi_MaChuong_DoKho_MaMon(item.MaChuong, "0", Mon_GT.MaMonHoc);
                foreach (CauHoiTbl chtbl in lst)
                {
                    CauHoi_GiaiThuatTbl ch = new CauHoi_GiaiThuatTbl(chtbl.MaCauHoi, chtbl.NoiDung, chtbl.ThoiGian, chtbl.DoKho, item.MaChuong);
                    lstQuanThe.Add(ch);
                }
            }
        }
        List<GhepCapDeThi_GiaiThuatTbl> lstGepCap;
        private void btnGhepCap_Click(object sender, EventArgs e)
        {
            lvwGhepCap.Items.Clear();
            pageSlider.SelectedPage = pageGhepCap;
            lstGepCap = new List<GhepCapDeThi_GiaiThuatTbl>();
            lstGepCap =  gtgen.GhepCap(dsDeThi);
            int i=1;
            foreach (GhepCapDeThi_GiaiThuatTbl cap in lstGepCap)
            {
                ListViewItem item = new ListViewItem();
                item.Text = i.ToString();
                item.SubItems.Add(cap.dethi1.TENDETHI);
                item.SubItems.Add(cap.dethi2.TENDETHI);
                lvwGhepCap.Items.Add(item);
                i++;
            }
            btnGhepCap.Enabled = false;
            btnLaiGhep.Enabled = true;
        }
        Random random = new Random();
        private void KhoiTaoQuanThe()
        {
            do
            {
                SoDeThiBanDau = random.Next(10, 100);
            } while (SoDeThiBanDau % 2 == 1);
            dsDeThi = new List<DeThi_GiaiThuatTbl>();
            dsDeThi = gtgen.DanhSachDeThi(SoDeThiBanDau, DeThi_GT.SoCauHoi, lstQuanThe);
            dsDeThi = gtgen.DoThichNghi(dsDeThi,ArrChuong_GT,DeThi_GT);
        }
        private void btnLaiGhep_Click(object sender, EventArgs e)
        {
            lstboxDeThi_LaiGhep.DataSource = null;
            pageSlider.SelectedPage = pageLaiGhep;
            dsDeThi = gtgen.LaiGhep(lstGepCap);
            dsDeThi = gtgen.DoThichNghi(dsDeThi, ArrChuong_GT, DeThi_GT);
            lstboxDeThi_LaiGhep.DataSource = dsDeThi;
            lstboxDeThi_LaiGhep.DisplayMember = "TenDeThi";
            lstboxDeThi_LaiGhep.ValueMember = "MaDeThi";
            btnLaiGhep.Enabled = false;
            btnDotBien.Enabled = true;
        }

        private void btnDotBien_Click(object sender, EventArgs e)
        {
            pageSlider.SelectedPage = pageDotBien;
            btnDotBien.Enabled = false;
            btnGiaiThuat.Enabled = true;
            TiLeDotBien = random.Next(50) / 1000;
            dsDeThi = gtgen.DotBien(dsDeThi, TiLeDotBien);
            dsDeThi = gtgen.DoThichNghi(dsDeThi, ArrChuong_GT, DeThi_GT);
            lstDeThi_Dotbien.DataSource = dsDeThi;
            lstDeThi_Dotbien.DisplayMember = "TenDeThi";
            lstDeThi_Dotbien.ValueMember = "MaDeThi";
        }

        private void lstDeThi_khoiTao_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<CauHoi_GiaiThuatTbl> lst = null;
            dgvCauhoi_khoitao.DataSource = null;
            if (lstDeThi_khoiTao.SelectedIndex>=0)
            {
                ThuocTinh(lstDeThi_khoiTao.SelectedValue.ToString());
                lst = Loaddgv(lstDeThi_khoiTao.SelectedValue.ToString());
            }
            if (lst == null || lst.Count == 0)
                return;
            dgvCauhoi_khoitao.DataSource = lst;
            dgvCauhoi_khoitao.Columns["NOIDUNG"].Width = 520;
            dgvCauhoi_khoitao.Columns[0].Visible = false;
        }

        private List<CauHoi_GiaiThuatTbl> Loaddgv(string made)
        {
            List<CauHoi_GiaiThuatTbl> lst = null;
            foreach (DeThi_GiaiThuatTbl dethi in dsDeThi)
            {
                if (dethi.MADETHI == made)
                {
                    lst = new List<CauHoi_GiaiThuatTbl>();
                    lst = dethi.lstCauHoi;
                    break;
                }
            }
            return lst;
        }

        private void lstDeThi_LaiGhep_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<CauHoi_GiaiThuatTbl> lst = null;
            dgvCauHoi_LaiGhep.DataSource = null;
            if (lstboxDeThi_LaiGhep.SelectedIndex >= 0)
            {
                ThuocTinh(lstboxDeThi_LaiGhep.SelectedValue.ToString());
                lst = Loaddgv(lstboxDeThi_LaiGhep.SelectedValue.ToString());
            }
            if (lst == null || lst.Count == 0)
                return;
            dgvCauHoi_LaiGhep.DataSource = lst;
            dgvCauHoi_LaiGhep.Columns["NOIDUNG"].Width = 480;
            dgvCauHoi_LaiGhep.Columns[0].Visible= false;
        }

        private void ThuocTinh(string func)
        {
            string time="";
            double dothichnghi=0;
            List<CauHoi_GiaiThuatTbl> dscauhoi = new List<CauHoi_GiaiThuatTbl>();
            foreach (DeThi_GiaiThuatTbl item in dsDeThi)
            {
                if (item.MADETHI == func)
                {
                    dscauhoi = item.lstCauHoi;
                    dothichnghi =  Math.Round(item.DoThichNghi, 2);
                    time = item.THOIGIAN.ToString();
                    break;
                }
            }
            int rk = 0, k = 0, vua = 0, d = 0, rd = 0;
            int[] count_cauhoi_chuong = new int[ArrChuong_GT.Count];
            int ch = 0;
            for (int i = 0; i < count_cauhoi_chuong.Count(); i++)
            {
                count_cauhoi_chuong[i] = 0;
            }
            foreach (CauHoi_GiaiThuatTbl cauhoi in dscauhoi)
            {
                ch++;
                if (cauhoi.DoKho == 1)
                    rd++;
                if (cauhoi.DoKho == 2)
                    d++;
                if (cauhoi.DoKho == 3)
                    vua++;
                if (cauhoi.DoKho == 4)
                    k++;
                if (cauhoi.DoKho == 5)
                    rk++;
                for (int i = 0; i < count_cauhoi_chuong.Count(); i++)
                {
                    if (cauhoi.MaChuong == ArrChuong_GT[i].MaChuong)
                        count_cauhoi_chuong[i]++;
                }
            }
            lblDoKho_RD.Text = "Rất Dễ: " + (rd * 100 / DeThi_GT.SoCauHoi).ToString() + " %  (<font color='#B02B2C'>" + DeThi_GT.RatDe + "%</font>)";
            lblDoKho_D.Text = "Dễ : " + (d * 100 / DeThi_GT.SoCauHoi).ToString() + " %  (<font color='#B02B2C'>" + DeThi_GT.De + "%</font>)";
            lblDoKho_Vua.Text = "Vừa : " + (vua * 100 / DeThi_GT.SoCauHoi).ToString() + " %  (<font color='#B02B2C'>" + DeThi_GT.Vua + "%</font>)";
            lblDoKho_K.Text = "Khó : " + (k * 100 / DeThi_GT.SoCauHoi).ToString() + " %  (<font color='#B02B2C'>" + DeThi_GT.Kho + "%</font>)";
            lblDoKho_RK.Text = "Rất Khó : " + (rk * 100 / DeThi_GT.SoCauHoi).ToString() + " %  (<font color='#B02B2C'>" + DeThi_GT.RatKho + "%</font>)";
            CreateControllexpDeThi(time, dothichnghi.ToString(), count_cauhoi_chuong);
           expDoKho.Refresh();
            expDeThi.Refresh();
        }

        private void CreateControllexpDeThi(string thoigian, string dothichnghi,int[] countChuong)
        {
            expDeThi.SubItems.Clear();
            LabelItem lblThoiGian = new LabelItem();
            lblThoiGian.Text = "Thời Gian: " + thoigian +" phút  (<font color='#B02B2C'>"+DeThi_GT.ThoiGian.ToString()+"</font>)";
            LabelItem lblDoThichNghi = new LabelItem();
            lblDoThichNghi.Text = "Độ thích nghi: " + dothichnghi + "  (<font color='#B02B2C'>-1.0</font>)";
            expDeThi.SubItems.Add(lblThoiGian);
            expDeThi.SubItems.Add(lblDoThichNghi);
            LabelItem lblitem;
            for (int i = 0; i < countChuong.Count(); i++)
            {
                lblitem = new LabelItem();
                if (ArrChuong_GT[i].TenChuong.Length > 13)
                    lblitem.Text = countChuong[i] * 100 / DeThi_GT.SoCauHoi + " %  (<font color='#B02B2C'>" + ArrChuong_GT[i].DoKho + "%</font>) - " + ArrChuong_GT[i].TenChuong.Substring(0,13)+"...";
                else
                    lblitem.Text = countChuong[i] * 100 / DeThi_GT.SoCauHoi + " %  (<font color='#B02B2C'>" + ArrChuong_GT[i].DoKho + "%</font>) - " + ArrChuong_GT[i].TenChuong;
                lblitem.Tooltip = ArrChuong_GT[i].TenChuong;
                lblitem.Name = "lblChuong" + i;
                expDeThi.SubItems.Add(lblitem);
            }
        }

        private void lstDeThi_Dotbien_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<CauHoi_GiaiThuatTbl> lst = null;
            dgvCauHoi_Dotbien.DataSource = null;
            if (lstDeThi_Dotbien.SelectedIndex >= 0)
            {
                ThuocTinh(lstDeThi_Dotbien.SelectedValue.ToString());
                lst = Loaddgv(lstDeThi_Dotbien.SelectedValue.ToString());
            }
            if (lst == null || lst.Count == 0)
                return;
            dgvCauHoi_Dotbien.DataSource = lst;
            dgvCauHoi_Dotbien.Columns["NOIDUNG"].Width = 520;
            dgvCauHoi_Dotbien.Columns[0].Visible = false;
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn chắc chắn muốn thoát?","",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            }
        }

        private void buttonX1_Click_1(object sender, EventArgs e)
        {
            btnReSet.Enabled = true;
            btnGiaiThuat.Enabled = false;
            var xk = (from ele in dsDeThi
                      orderby ele.DoThichNghi descending
                      select ele).Take(1);
            decantao = xk.ToList()[0];
            DeThi_GiaiThuatTbl de = xk.ToList()[0];
            TaoexpGiaiThuat(0, 1, dsDeThi.Count, lstQuanThe.Count);
            List<CauHoi_GiaiThuatTbl> lst = null;
            ThuocTinh(de.MADETHI);
            lst = Loaddgv(de.MADETHI);
            dgvKetQuaGT.DataSource = null;
            dgvKetQuaGT.DataSource = lst;
            dgvKetQuaGT.Columns["NOIDUNG"].Width = 630;
            dgvKetQuaGT.Columns[0].Visible= false;
            pageSlider.SelectedPage = pageGiaiThuat;
            btnLuu.Enabled = true;
            expGiaiThuat.Expanded = true;
            expGiaiThuat.Refresh();
        }

        private void TaoexpGiaiThuat(double p1, int p2, int p3, int p4)
        {
            expGiaiThuat.SubItems.Clear();
            LabelItem lblThoiGianThucHien_GT = new LabelItem();
            if (p1 == 0)
                lblThoiGianThucHien_GT.Text = "Thời gian thực hiện:";
            else
                lblThoiGianThucHien_GT.Text = "Thời gian thực hiện: " + p1 + " giây";
            LabelItem lblSoLanThucHien_GT = new LabelItem();
            lblSoLanThucHien_GT.Text = "Số lần thực hiện: " + p2;
            LabelItem lbltongsodethi_GT = new LabelItem();
            lbltongsodethi_GT.Text = "Tổng số đề thi: " + p3;
            LabelItem lblNganhangcauhoi_GT = new LabelItem();
            lblNganhangcauhoi_GT.Text = "Ngân hàng câu hỏi: " + p4;
            expGiaiThuat.SubItems.Add(lblThoiGianThucHien_GT);
            expGiaiThuat.SubItems.Add(lblSoLanThucHien_GT);
            expGiaiThuat.SubItems.Add(lbltongsodethi_GT);
            expGiaiThuat.SubItems.Add(lblNganhangcauhoi_GT);
        }
        int tempT = 0;
        private void GiaithuatTuDong()
        {
            tempT = 0;
            Stopwatch timeout = new Stopwatch();
            timeout.Start();
            KhoiTaoQuanThe();
            while (tempT < 1000 && timeout.Elapsed.Seconds < 5)
            {
                tempT++;
                dsDeThi = gtgen.giaithuat(dsDeThi);
                dsDeThi = gtgen.DoThichNghi(dsDeThi, ArrChuong_GT, DeThi_GT);
                var k = (from ele in dsDeThi
                         orderby ele.DoThichNghi descending
                         select ele).Take(1);
                if (k.ToList()[0].DoThichNghi > -1.1)
                    break;
            }
            timeout.Stop();
            var xk = (from ele in dsDeThi
                      orderby ele.DoThichNghi descending
                      select ele).Take(1);
            decantao = xk.ToList()[0];
            DeThi_GiaiThuatTbl de = xk.ToList()[0];
            double thoigianth = (timeout.Elapsed.TotalSeconds.ToString().Length >= 6) ? Math.Round(timeout.Elapsed.TotalSeconds, 5) : timeout.Elapsed.TotalSeconds;
            TaoexpGiaiThuat(thoigianth, tempT, dsDeThi.Count, lstQuanThe.Count);
            List<CauHoi_GiaiThuatTbl> lst = null;
            ThuocTinh(de.MADETHI);
            lst = Loaddgv(de.MADETHI);
            dgvKetQuaGT.DataSource = null;
            dgvKetQuaGT.DataSource = lst;
            dgvKetQuaGT.Columns["NOIDUNG"].Width = 630;
            dgvKetQuaGT.Columns[0].Visible = false;
            pageSlider.SelectedPage = pageGiaiThuat;
            expGiaiThuat.Expanded = true;
            expGiaiThuat.Refresh();
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
                BusinessLogicLayer bll = new BusinessLogicLayer();
                DeThiTbl dthi = new DeThiTbl();
                NguoiradeBll nrd = new NguoiradeBll();
                dthi.MANGUOIRADE = nrd.Manguoirade(this.user);
                dthi.TENDETHI = lbltendethi.Text;
                dthi.SOCAUHOI = int.Parse(lblSoCauhoi.Text);
                dthi.NGAYTAODE = DateTime.Now;
                dthi.THOIGIAN = int.Parse(lblThoiGian.Text);
                DethiBLL dt = new DethiBLL();
                List<string> lst = bll.ConvertCauHoiGTToCauHoi(decantao.lstCauHoi);
                if (!dt.ThemDethi(dthi, lst))
                {
                    MessageBox.Show("Không lưu đề thi được");
                    return;
                }
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnReSet_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn muốn thực hiện lại giải thuật Gen?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                pageSlider.SelectedPage = pageLoad;
                lstDeThi_khoiTao.DataSource = null;
                if (GTTuDong)
                    GiaithuatTuDong();
                else
                {
                    btnKhoiTao.Enabled = true;
                    btnReSet.Enabled = false;
                }
            }
        }
    }
}